package com.zxq.kingofbots.consumer;

import com.alibaba.fastjson2.JSONObject;
import com.zxq.kingofbots.consumer.utils.Game;
import com.zxq.kingofbots.mapper.RecordMapper;
import com.zxq.kingofbots.mapper.UserMapper;
import com.zxq.kingofbots.pojo.User;
import com.zxq.kingofbots.consumer.utils.JwtAuthentication;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint("/websocket/{token}")
public class WebSocketServer {
    //线程安全的哈希表
    public static ConcurrentHashMap<Integer,WebSocketServer> users=new ConcurrentHashMap<>();
    final private static CopyOnWriteArraySet<User> matchPoll = new CopyOnWriteArraySet<>();
    //当前链接的用户
    private User user;
    //后端向前端发信息,每个链接用session维护
    private Session session = null;

    private static UserMapper userMapper;
    public static RecordMapper recordMapper;

    private Game game=null;

    @Autowired
    public void setUserMapper(UserMapper userMapper){
        WebSocketServer.userMapper=userMapper;
    }

    @Autowired
    public void setRecordMapper(RecordMapper recordMapper){
        WebSocketServer.recordMapper=recordMapper;
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) throws IOException {
        // 建立连接
        System.out.println("connected!");
        this.session=session;
        //为了方便调试，初阶段只把token当成userId看
        Integer userId = JwtAuthentication.getUserId(token);
        this.user=userMapper.selectById(userId);
        if (this.user!=null) {
            users.put(userId,this);
        } else {
            this.session.close();
        }
    }

    @OnClose
    public void onClose() {
        // 关闭链接
        System.out.println("close");
        if(this.user!=null){
            users.remove(this.user.getId());
        }
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        // 从Client接收消息
        System.out.println("receive message");
        JSONObject data = JSONObject.parseObject(message);
        String event = data.getString("event");
//        System.out.println(event);
        if ("start-matching".equals(event)) {
            startMatching();
        } else if ("stop-matching".equals(event)) {
            stopMatching();
        }   else if("move".equals(event)){
            int d=data.getIntValue("direction");
            move(d);
        }
    }

    private void move(int d) {
        if(game.getPlayerA().getId().equals(user.getId())){
            game.setNextStepA(d);
        }else if(game.getPlayerB().getId().equals(user.getId())){
            game.setNextStepB(d);
        }
    }

    private void startMatching() {
        System.out.println("start");
        matchPoll.add(this.user);
        while (matchPoll.size()>=2){
            Iterator<User> iterator = matchPoll.iterator();
            User a = iterator.next();
            User b = iterator.next();
            matchPoll.remove(a);
            matchPoll.remove(b);

            Game game = new Game(13, 14, 20,a.getId(),b.getId());
            game.createMap();
            //新创建的游戏实例赋值给参与游戏的用户，使得每个用户都能访问和操作当前游戏的状态和逻辑。
            users.get(a.getId()).game=game;
            users.get(b.getId()).game=game;
            game.start();

            JSONObject respGame=new JSONObject();
            respGame.put("a_id",a.getId());
            respGame.put("a_sx",game.getPlayerA().getSx());
            respGame.put("a_sy",game.getPlayerA().getSy());
            respGame.put("b_id",b.getId());
            respGame.put("b_sx",game.getPlayerB().getSx());
            respGame.put("b_sy",game.getPlayerB().getSy());
            respGame.put("map",game.getG());

            JSONObject respA = new JSONObject();
            respA.put("event","match-success");
            respA.put("opponent_username",b.getUsername());
            respA.put("opponent_photo",b.getPhoto());
            respA.put("game",respGame);
            //用users获取a的链接
            users.get(a.getId()).SendMessage(respA.toJSONString());

            JSONObject respB = new JSONObject();
            respB.put("event","match-success");
            respB.put("opponent_username",a.getUsername());
            respB.put("opponent_photo",a.getPhoto());
            respB.put("game",respGame);
            //用users获取b的链接
            users.get(b.getId()).SendMessage(respB.toJSONString());
        }
    }

    private void stopMatching() {
        System.out.println("stop");
        matchPoll.remove(this.user);
    }



    //后端向前端发信息
    public void SendMessage(String message){
        //同步
        synchronized (this.session){
            try {
                this.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }
}
